package com.ys.malini.dao.impl;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ys.malini.dao.HibernatePagerManager;
import com.ys.malini.dao.IShowroomDao;
import com.ys.malini.model.TShowroominfo;
import com.ys.malini.util.Constant;
import com.ys.malini.util.PictureUpLoad;
import com.ys.malini.web.form.RoomForm;

/**
 * 展厅信息管理
 * 
 * @author Administrator
 * 
 */
public class ShowroomDao extends HibernateDaoSupport implements IShowroomDao {

	public String addRoomInfo(RoomForm formbean) {
		
			String savepath="";
			String fileName="";
			String message="";
			MultipartRequestHandler handle = formbean.getMultipartRequestHandler();
			Hashtable hashTable = handle.getFileElements();
			Collection cln = hashTable.values();
			Iterator iterator = cln.iterator();
			while (iterator.hasNext()) {
				FormFile file = (FormFile) iterator.next();
				String path=formbean.getPath();
				savepath=Constant.pictureDirectory+ File.separator+"zt"+File.separator;
				File fileDis = new File(path);
				fileDis.mkdirs();
				if (PictureUpLoad.isDirectoryExists(path) == false)
					return null;
				if (file.getFileName() == null)
					return null;
				if (file.getFileName().equals("")){
					continue;
				}
				if (file.getFileSize() > Constant.pictureSize)
					return null;
				if (!PictureUpLoad.isValidFile(file.getFileName()))
					return null;
				try {
					String pathSrc = path + PictureUpLoad.rebuildFileName(file.getFileName());
					String savepathsrc=savepath+PictureUpLoad.rebuildFileName(file.getFileName());
					
					InputStream in = file.getInputStream();
					OutputStream out = new FileOutputStream(pathSrc);// "/"表示保存的路径可以修改为"load/"
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
						out.write(buffer, 0, bytesRead);
					}
					String pathDest = path + PictureUpLoad.generateSmallPic(file.getFileName());
					String savepathDest=savepath+ PictureUpLoad.generateSmallPic(file.getFileName());
						
					PictureUpLoad.copyfile(pathSrc, pathDest);
					/*生成缩略图*/
					File stadimgfile2 = new File(pathSrc);
					/*图片缓存*/
					BufferedImage img2 = ImageIO.read(stadimgfile2);
//					  bufimage = g2d.getDeviceConfiguration().createCompatibleImage((int)imageRect.getWidth(), (int)imageRect.getHeight(), Transparency.BITMASK);
//					  g2d.dispose();
//					  g2d=bufimage.createGraphics();
					  
					/*得到图片的宽和高*/
					double width = img2.getWidth();
					double height = img2.getHeight();
					double rateh = Constant.miniheight / height;
					double ratew = Constant.miniwidth / width;
					/*获得适合的缩放比率，即以在规定缩略尺寸中完整显示图片内容的同时又保证最大的缩放比率*/
					double rate = Math.min(ratew, rateh);
					rate = (Math.rint((rate * 100) + 0.5)) / 100;
					BufferedImage imgmini = new BufferedImage(Constant.miniwidth,
							Constant.miniheight, BufferedImage.TYPE_USHORT_565_RGB);

					Graphics2D gmini = imgmini.createGraphics();
					gmini.setBackground(Color.darkGray);
					gmini.clearRect(0, 0, Constant.miniwidth, Constant.miniheight);
					AffineTransform trans = new AffineTransform();
					trans.scale(rate, rate);
					AffineTransformOp op = new AffineTransformOp(trans,
							AffineTransformOp.TYPE_BILINEAR);
					gmini.drawImage(img2, op, (int) (Constant.miniwidth - (width * rate)) / 2,
							(int) (Constant.miniheight - (height * rate)) / 2);
					ImageIO.write(imgmini, "jpg", stadimgfile2);
					
					if(fileName==""){
						//fileName = pathSrc+"@"+pathDest;
						savepath=savepathsrc+"@"+savepathDest;
					}else{
						//fileName = fileName + "#" +pathSrc+"@"+pathDest;
						savepath = savepath + "#" +savepathsrc+"@"+savepathDest;
					}
					out.close();
					in.close();
					TShowroominfo roominfo = new TShowroominfo();
					roominfo.setAdress(formbean.getAdress());
					
					String[] fileArr1 = savepath.split("#");
					
					for (int i = 0; i < fileArr1.length; i++) {
						String[] fileArr2 = fileArr1[i].split("@");
						for (int j = 0; j < fileArr2.length; j++) {
							System.out.println("filename"+j+"=" + fileArr2[j]);
						}						
						roominfo.setBigimages(fileArr2[1]);
						roominfo.setSmimages(fileArr2[0]);
					}
					
					roominfo.setZtname(formbean.getZtname());
					getSession().save(roominfo);
					
				} catch (Exception e) {
					e.printStackTrace();
					message="新增失败";
				}
			}
			
			
			message="新增成功";
			
			return message;
	
		
		
	}

	public String deleteRoomInfo(Map map) {
		String message="删除失败";
		String roomId=(String) map.get("roomId");
		StringBuffer hql = new StringBuffer(" delete TShowroominfo o where 1=1  and roomId='"+roomId+"' ");
		
		Query query = getSession().createQuery(hql.toString());		
		query.executeUpdate();
		message="删除成功！";
		return message;
	}

	public List<TShowroominfo> query(RoomForm formbean, boolean isPager) {
		System.out.println(".................");
		String hsql = " from TShowroominfo order by  roomId desc";
		System.out.println("-----" + hsql);
		List<TShowroominfo> roomlist = null;
		if (isPager) {
			roomlist = HibernatePagerManager.searchPaginated(getSession(), hsql
					.toString());
		} else {
			roomlist = getHibernateTemplate().find(hsql);
		}

		return roomlist;
	}

	public TShowroominfo queryRoomInfoById(String roomId) {
		String hsql=" from TShowroominfo where roomId='"+roomId+"'";
		List list =getHibernateTemplate().find(hsql);
		TShowroominfo roominfo =list!=null&&list.size()>0?(TShowroominfo)list.get(0):null;
		return roominfo;
	}

	public String updateRoomInfoById(RoomForm formbean) {
		// TODO Auto-generated method stub
		return null;
	}


}
